/*
* MSSQL10.GeometryFactory - point geometry handler
* 
* initial implementation : 14.11.2008
*
* Copyright (c) Adam Sida, asida@centrum.cz.
* All rights reserved.
* 
* for license see Petra.Gis.License.txt
*/
using System;
using System.Collections.Generic;
//using System.Text;
using System.IO;
using Petra.Gis.Geometry;
using Petra.Gis.Geometry.Support;
using Petra.Gis.DataServices.MSSQL10.Support;

namespace Petra.Gis.DataServices.MSSQL10
{
  public partial class GeometryFactory
  {

    /// <summary>
    /// converts sqlserver binary stream with point geometry
    /// to <c>Petra.Gis.Geometry.Point</c>
    /// </summary>
    /// <param name="mBReader">input binary reader</param>
    /// <param name="parentGeomType"></param>
    /// <returns>new instance of geometry</returns>
    private static GeometryBase binaryToPoint(BinaryReader mBReader, System.Type parentGeomType)
    {
      //skip SRID
      mBReader.BaseStream.Position += 4;

      //read coordlist type
      SqlSvrCoordListTypeEnum cListType = (SqlSvrCoordListTypeEnum)mBReader.ReadInt16();

      CoordinateList Coords = new CoordinateList(((SqlSvrMemoryStream)mBReader.BaseStream).GetBuffer(), (int)mBReader.BaseStream.Position, 1, Dimension.dim2D);
      Point oGeom = new Point();
      oGeom.coordList = Coords;

      if (cListType == SqlSvrCoordListTypeEnum.PointZM)
      {
        //skip Z, useless in mssql10
        mBReader.BaseStream.Position += 24;
        oGeom.Rotation = mBReader.ReadDouble();
      }

      return oGeom;
    }





    /// <summary>
    /// converts <c>Petra.Gis.Geometry.Point</c> into sqlserver 10 binary stream
    /// </summary>
    /// <param name="geometry">Point geometry</param>
    /// <returns>byte[] with encoded geometry</returns>
    private static byte[] pointToBinary(GeometryBase geometry)
    {
      int lBlobSize;

      Point _tmpPoint = (Point)geometry;

      lBlobSize = 4 + 2 + 16;

      if (_tmpPoint.Rotation != 0)
        lBlobSize += 32;

      System.IO.MemoryStream oIMStream = new System.IO.MemoryStream(lBlobSize);
      System.IO.BinaryWriter mBWriter = new System.IO.BinaryWriter(oIMStream);

      oIMStream.Position = 0;

      mBWriter.Write((Int32)0); //SRID
      if (_tmpPoint.Rotation != 0)
        mBWriter.Write((Int32)SqlSvrCoordListTypeEnum.PointZM); //coordlist type
      else
        mBWriter.Write((Int32)SqlSvrCoordListTypeEnum.Point); //coordlist type

      mBWriter.Write(_tmpPoint.coordList.ToArray(Dimension.dim2D));

      if (_tmpPoint.Rotation != 0)
      {
        mBWriter.Write((double)0x000000000000F8FF);
        mBWriter.Write((double)0x0000000000000000); //Z = 0, not used with sqlserver10
        mBWriter.Write((double)0x000000000000F8FF);
        mBWriter.Write(_tmpPoint.Rotation);
      }

      return oIMStream.ToArray();
    }



  }

}
